package com.crpc.core.loadBalance.impl;

import com.crpc.core.CrpcBootStrap;
import com.crpc.core.loadBalance.AbstractLoadBalance;
import com.crpc.core.loadBalance.Selector;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author wzy
 * @version 1.0
 * @description: 轮训负载均衡策略
 * @date 2023/9/30 21:29
 */
@Slf4j
public class MinimumResponseLoadBalance extends AbstractLoadBalance {

    @Override
    public Selector getSelector(List<InetSocketAddress> inetSocketAddressList) {

        return new MinimumResponseSelector();
    }

    private static class MinimumResponseSelector implements Selector {
        @Override
        public InetSocketAddress getNext() {
            Map.Entry<Long, Channel> firstEntry = CrpcBootStrap.ANSWER_TIME.firstEntry();
            if (firstEntry != null) {
                log.info("选取最短响应时间：{}的节点是：{}", firstEntry.getKey(), firstEntry.getValue().remoteAddress());
                return (InetSocketAddress) firstEntry.getValue().remoteAddress();
            } else {
                //从缓存中选择一个可用的
                Map<InetSocketAddress, Channel> channelMap = CrpcBootStrap.CHANNEL_MAP;
                ArrayList<Channel> channels = new ArrayList<>(channelMap.values());
                Collections.shuffle(channels);
                return (InetSocketAddress) channels.get(0).remoteAddress();
            }
        }
    }
}
